package utils

import (
	"gitee.com/chejiangyi/bsfgo/core/base2"
	"github.com/go-resty/resty/v2"
	"net/http"
	"sync"
	"time"
)

var HttpUtil = &HttpUtilTool{}

type HttpUtilTool struct {
	DefaultClient *resty.Client
	once          sync.Once
}

func (m *HttpUtilTool) GetDefaultClient() *resty.Client {
	m.once.Do(func() {
		client := resty.New()
		// 优化连接池配置
		transport := &http.Transport{
			MaxIdleConns:        base2.BsfConfigInstance.GetHttpMaxIdleConns(),
			MaxIdleConnsPerHost: base2.BsfConfigInstance.GetHttpMaxIdleConnsPerHost(),
			IdleConnTimeout:     time.Duration(base2.BsfConfigInstance.GetHttpIdleConnTimeoutSeconds()) * time.Second,
			DisableKeepAlives:   base2.BsfConfigInstance.GetHttpDisableKeepAlives(),
		}
		client.SetTransport(transport).
			SetTimeout(time.Duration(base2.BsfConfigInstance.GetHttpSetTimeoutSeconds()) * time.Second). // 单次请求超时
			SetRetryCount(base2.BsfConfigInstance.GetHttpSetRetryCount())                                // 自动重试
		//SetDebug(true)
		m.DefaultClient = client
	})

	return m.DefaultClient
}
